package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description UserIntercept
 * @Author Lwj
 * @Date 2024-08-31-10:15
 */
@Component
@Slf4j
public class UserIntercept implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.静态资源要放行（非处理器（控制器的方法）要放行）
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //2.从请求头中获取authorization(token)
        String token = request.getHeader("authorization");
        log.info("token:{}", token);
        //3.判断token是否为空，抛出异常友好信息
        if (ObjectUtil.isEmpty(token)) {
            log.info("令牌为空！");
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //4.解析token,不合法，抛出异常友好信息
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        } catch (Exception e) {
            log.info("用户登录令牌不合法，原因：{}", e.getMessage());
            throw new BaseException(BasicEnum.LOGIN_FAIL);
        }
        //5.从token获取载荷得到登录人id
        //Long userId = (Long) claims.get(Constants.JWT_USERID.toString());
        Long userId = MapUtil.get(claims, Constants.JWT_USERID, Long.class);
        //6、创建本地线程ThreadLocal
        UserThreadLocal.set(userId);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放本地线程数据
        UserThreadLocal.remove();
    }
}
